<template>
  <view class="fix-top-window">
    <view class="uni-header">
      <uni-stat-breadcrumb class="uni-stat-breadcrumb-on-phone" />
      <view class="uni-group">
        <uni-easyinput type="text" v-model="query.description" :placeholder="$t('common.placeholder.query')" />
        <button class="uni-button hide-on-phone" type="default" size="mini" @click="getData(1)">{{$t('common.button.search')}}</button>
        <button class="uni-button" type="primary" size="mini" @click="navigateTo('./edit')"
                v-if="uniIDHasPermission('wsa')">
          {{$t('common.button.add')}}
        </button>
        <button class="uni-button" size="mini" type="warn" v-if="uniIDHasPermission('wsd')" 
                :disabled="!tableData.selectedIndexArray.length" @click="removeDataByIds()">{{ $t('common.button.batchDelete') }}</button>
        <!-- #ifdef H5 -->
          <download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcel.data"
                          :type="exportExcel.type" :name="exportExcel.filename">
            <button class="uni-button" type="primary" size="mini">{{$t('common.button.exportExcel')}}</button>
          </download-excel>
        <!-- #endif -->
      </view>
    </view>
    <view class="uni-container">
      <uni-table ref="tableRef" :emptyText="$t('common.empty')" border stripe
                 type="selection" @selection-change="selectionChange">
        <uni-tr>
          <uni-th align="center" filter-type="select" :filter-data="getDictByType('SwiperType').options" width="100"
                  @filter-change="filterChange($event, 'type')">类型</uni-th>
          <uni-th align="center" width="150">轮播图图片</uni-th>
          <uni-th align="center" filter-type="search" width="100"
                  @filter-change="filterChange($event, 'description')">描述</uni-th>
          <uni-th align="center" width="80">排序</uni-th>
          <uni-th align="center" width="100">创建用户</uni-th>
          <uni-th align="center" filter-type="timestamp" sortable width="100"
                  @filter-change="filterChange($event, 'updateTime')">编辑时间</uni-th>
          <uni-th align="center" width="80">是否启用</uni-th>
          <uni-th align="center" width="180">操作</uni-th>
        </uni-tr>
        <uni-tr v-for="(item,index) in tableData.list" :key="index">
          <uni-td align="center">{{getDictText('SwiperType', item.type)}}</uni-td>
          <uni-td align="center">
            <image :src="cloudIdToUrl(item.picurl,{w:150})" mode="aspectFill" @click="previewImage(item.picurl,'picurl')"
                   style="width: 150px; height: 75px; border-radius: 5px; overflow: hidden;"></image>
          </uni-td>
          <uni-td align="center">{{item.description}}</uni-td>
          <uni-td align="center">{{item.sort}}</uni-td>
          <uni-td align="center">{{item.nickname}}</uni-td>
          <uni-td align="center"><uni-dateformat :date="item.updateTime" format="yyyy-MM-dd"></uni-dateformat></uni-td>
          <uni-td align="center">
            <switch v-if="uniIDHasPermission('wse')" :checked='item.enable' style="transform:scale(0.7)" @change="toggleFieldChange(item._id, 'enable')"/>
            <uni-tag v-else inverted="true" :text="item.enable? '已启用':'未启用'" :type="item.enable?'success':'error'" />
          </uni-td>
          <uni-td align="center">
            <view class="uni-group">
              <button class="uni-button" size="mini" type="primary" 
                      v-if="uniIDHasPermission('wse')" @click="navigateTo('./edit?id='+item._id, false)">
                {{ $t('common.button.edit') }}
              </button>
              <button class="uni-button" size="mini" type="warn" v-if="uniIDHasPermission('wsd')" @click="removeDataByIds([item._id])">{{ $t('common.button.delete') }}</button>
            </view>
          </uni-td>
        </uni-tr>
      </uni-table>
      <view class="uni-pagination-box">
        <uni-pagination show-iconn show-page-size :page-size="query.pageSize" v-model="query.page"
                        :total="tableData.total" @change="onPageChange" @pageSizeChange="changeSize" />
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useTableSearch } from '@/utils/composable.js'
import { cloudIdToUrl, formatDateTime } from '@/utils/common.js'
const tableRef = ref(null)
const wallpaperSwiperObj = uniCloud.importObject('iss-wallpaper')

// 导出Excel的字段定义
const exportExcel = ref({
  "filename": "iss-wallpaper-swiper.xls",
  "type": "xls",
  "fields": {
	"类型": "type",
	"轮播图片":"picurl",
    "描述": "description",
	"链接地址":"url",
    "排序": "sort",
    "创建用户": "nickname",
    "创建时间": "updateTime",
    "是否启用": "enable"
  },
  "data":[]
})

// 数据字典定义
const dictsRef = ref([{type:'SwiperType'}])

// 使用通用表格搜索逻辑
const {
  query, // 查询条件 ref对象
  tableData, // 列表数据集合 ref对象
  getData, // 获取列表数据 method
  removeDataByIds, // 根据选择删除记录
  toggleFieldChange, // 列表中某条记录状态变化事件 method
  selectionChange, // 列表选中记录变化 method
  onPageChange, // table当前页变化事件 method
  changeSize, // table每页显示条数变化事件 method
  filterChange, // table 某列筛选条件变化
  sortChange, // table 某列排序变化
  previewImage, // 列表图片预览
  navigateTo, // 调整页面，并建立返回刷新数据的通信机制
  getDictByType, // 根据type获得字典对象
  getDictText, // 获取列表中对应数据字典的文本
} = useTableSearch({
  title: '轮播图',
  tableRef,
  dictsRef,
  searchform: {
    description: '',
    type: '',
    enable: undefined,
    createTime: []
  },
  getList: wallpaperSwiperObj.getList_swiper,
  columnToggle: wallpaperSwiperObj.columnToggle_swiper,
  remove: wallpaperSwiperObj.remove_swiper,
  onGetDataSucceed: (data)=>{
	// 更改联表查询的数据格式
	tableData.value.list = data.list.map(item => {
		// 创建一个新对象，包含原对象的所有属性
		const newItem = {
			...item,
			// 提取classid数组中的_id作为新的classid
			_uid: item._uid[0]._id,
			// 添加classiname字段，值为classid数组中第一个元素的name
			nickname: item._uid[0].nickname
		};
		return newItem;
	})
    // 当列表获得数据后，针对导出数据还是要做一些处理
    exportExcel.value.data = tableData.value.list.map(item => {
      // 创建一个新的对象，避免直接修改原对象
      const newItem = {...item}
      // 组合成 yyyy-MM-dd 格式
      newItem.updateTime = formatDateTime(item.updateTime)
      newItem.enable = item.enable ? '已启用' : '未启用'
	  newItem.target = item.target == 'self' ? '内部链接':'外部链接'
	  newItem.type = getDictText('SwiperType', item.type)
      return newItem
    })
  }
})
</script>

<style scoped lang="scss">
.uni-tag {
  display: inline-block;
}
/* 解决 uni-app uni-table 横向滚动条导致左侧边框高度异常问题 */
::v-deep .table--border {
  border: none;
}

::v-deep .uni-table {
  border: 1px solid #ebeef5;
  border-right: none;
  border-bottom: none;
}

::v-deep .uni-table-th, 
::v-deep .uni-table-td {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}
</style>    